/*
 *
 *
 * Created on 24 de abril de 2008, 06:49 PM
 */
package org.contabilidad.morosidad.inicial;

import org.mybeans.Sesion;
import org.mybeans.RemolquesBeans;
import org.mybeans.VigenciasExpiradasBeans;
import org.remolques.busquedas.RemolquesBusquedaConPlacaFrame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author  avbravo
 */
public class MorosidadInicialRemolquesConsultarFrame extends javax.swing.JFrame {

    Sesion sesion;
    RemolquesBeans remolquesBeans;
    VigenciasExpiradasBeans vigenciasExpiradasBeans;
    int fila = -1;
    DefaultTableModel modelo;
    String Placa;
    int idRemolque;
    boolean focoBuscar = false;

    public MorosidadInicialRemolquesConsultarFrame() {
        initComponents();
        sesion = new Sesion();
        remolquesBeans = new RemolquesBeans();
        vigenciasExpiradasBeans = new VigenciasExpiradasBeans();
        jTextFieldTotalAdeudado.setText("");

        /*
         * Fondo
         */

         
         
         

        jPanel3.setOpaque(false);
        setContentPane(jPanel3);
        /*
         * fondo
         */
           

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldPlaca = new javax.swing.JTextField();
        jTextFieldRemolque = new javax.swing.JTextField();
        jButtonBuscar = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldTotalAdeudado = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Morosidad Inicial de Remolque");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Placa");

        jLabel2.setText("Remolque");

        jTextFieldPlaca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldPlacaActionPerformed(evt);
            }
        });

        jTextFieldRemolque.setEditable(false);

        jButtonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/search.png"))); // NOI18N
        jButtonBuscar.setToolTipText("Buscar");
        jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Cerrar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "codigo", "Regimen", "Inicial", "Actual", "Fecha", "Año"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                true, false, false, false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(5).setResizable(false);

        jLabel3.setText("Total Adeudado");

        jTextFieldTotalAdeudado.setEditable(false);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30)
                        .addComponent(jButtonBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldRemolque, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 719, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addContainerGap(524, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldTotalAdeudado, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jTextFieldPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(28, 28, 28))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jButtonBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                                .addGap(1, 1, 1))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTextFieldRemolque, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldTotalAdeudado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed

    RemolquesBusquedaConPlacaFrame remolquesBusquedaConPlacaFrame = new RemolquesBusquedaConPlacaFrame();
    remolquesBusquedaConPlacaFrame.setLocationRelativeTo(null);
    remolquesBusquedaConPlacaFrame.setVisible(true);
    focoBuscar = true;
}//GEN-LAST:event_jButtonBuscarActionPerformed

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed

    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jTextFieldPlacaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldPlacaActionPerformed
    CargarRemolques();

}//GEN-LAST:event_jTextFieldPlacaActionPerformed

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
    // TODO add your handling code here:
    if (focoBuscar) {
        Actualizar();
    }
    focoBuscar = false;
}//GEN-LAST:event_formWindowGainedFocus

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MorosidadInicialRemolquesConsultarFrame().setVisible(true);
            }
        });
    }

    public void CargarMorosidadInicial() {
        try {
            //Limpiar();
            String placa = jTextFieldPlaca.getText();
            String sql = "select vigenciasexpiradas.*, regimen.regimen from  vigenciasexpiradas, regimen where vigenciasexpiradas.idmunicipio=? and vigenciasexpiradas.id =? and vigenciasexpiradas.tipoid ='remolques' and vigenciasexpiradas.activo='si' and vigenciasexpiradas.idregimen = regimen.idregimen and regimen.idmunicipio=? and regimen.activo='si'";
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            PreparedStatement psquery = sesion.con.prepareStatement(sql);
            psquery.setObject(1, sesion.getIdmunicipio());
            psquery.setObject(2, idRemolque);
            psquery.setObject(3, sesion.getIdmunicipio());
            ResultSet rs = psquery.executeQuery();

            modelo = new DefaultTableModel();
            // Creamos las columnas.
            modelo.addColumn("codigo");
            modelo.addColumn("regimen");
            modelo.addColumn("inicial");
            modelo.addColumn("actual");
            modelo.addColumn("fecha");
            modelo.addColumn("año");
            Double totaladeudado = 0.0;
// Bucle para cada resultado en la consulta
            while (rs.next()) {
                // Se crea un array que será una de las filas de la tabla.
                Object[] fila = new Object[7]; // Hay tres columnas en la tabla

                fila[0] = rs.getString("idregimen");
                fila[1] = rs.getString("regimen");
                fila[2] = rs.getString("morosidadinicial");
                fila[3] = rs.getString("morosidadactual");
                totaladeudado += rs.getDouble("morosidadactual");
                Date fecha = rs.getDate("fecha");
                Format formatter;
                formatter = new SimpleDateFormat("dd/MM/yyyy");
                String s = formatter.format(fecha);
                fila[4] = s;
                fila[5] = rs.getInt("anio");
                modelo.addRow(fila);

            }
            jTextFieldTotalAdeudado.setText(String.valueOf(totaladeudado));
            this.jTable1.setModel(modelo);
            jTable1.setVisible(true);

            this.jTable1.addMouseListener(new MouseAdapter() {

                public void mouseClicked(MouseEvent e) {

                    fila = jTable1.rowAtPoint(e.getPoint());
                    int columna = jTable1.columnAtPoint(e.getPoint());
                    if ((fila > -1) && (columna > -1)) {
                        String idRegimen = String.valueOf(jTable1.getValueAt(fila, 0));
                        String regimen = String.valueOf(jTable1.getValueAt(fila, 1));
                        String SMorosidadInicial = String.valueOf(jTable1.getValueAt(fila, 2));
                        Double morosidadInicial = Double.parseDouble(SMorosidadInicial);
                        String SMorosidadActual = String.valueOf(jTable1.getValueAt(fila, 3));
                        Double morosidadActual = Double.valueOf(SMorosidadActual);
                        String fecha = String.valueOf(jTable1.getValueAt(fila, 4));
                        vigenciasExpiradasBeans.setIdRegimen(idRegimen);
                        vigenciasExpiradasBeans.setRegimen(regimen);
                        vigenciasExpiradasBeans.setMorosidadInicial(morosidadInicial);
                        vigenciasExpiradasBeans.setMorosidadActual(morosidadActual);



                    }
                }
            });
            TableColumn column = jTable1.getColumnModel().getColumn(1);
            column.setPreferredWidth(250);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

    }

 

    private void CargarRemolques() {

        try {
            String Placa = this.jTextFieldPlaca.getText();
            if (Placa == null || Placa.equals("")) {
                JOptionPane.showMessageDialog(this, "Ingrese la placa del remolque", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            remolquesBeans.setPlaca(Placa);

            if (remolquesBeans.ConsultarPorPlaca() == true) {

                if (remolquesBeans.getPlaca() == null || remolquesBeans.getPlaca().equals("")) {
                    JOptionPane.showMessageDialog(this, "Este remolque no tiene asiganda una placa...", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }


                remolquesBeans.setTipoId(remolquesBeans.getTipoId().toLowerCase());

                Actualizar();

            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }


    }

    private void Actualizar() {
        try {

            jTextFieldPlaca.setText(remolquesBeans.getPlaca());
            this.Placa = remolquesBeans.getPlaca();
            if (remolquesBeans.getIdRemolque() == -1) {
                this.idRemolque = 0;
                JOptionPane.showMessageDialog(this, "Este remolque no tiene un codigo asignado", "Advertencia", JOptionPane.WARNING_MESSAGE);
            } else {
                this.idRemolque = remolquesBeans.getIdRemolque();
            }

            String dueno = "";
            if (remolquesBeans.getDueno() == null) {
                dueno = "";
            } else {
                dueno = " Dueño " + remolquesBeans.getDueno();
            }
            jTextFieldRemolque.setText(remolquesBeans.getMarca() + " Modelo: " + remolquesBeans.getModelo() + dueno);

            String TipoId = remolquesBeans.getTipoId();
            String idOld = remolquesBeans.getId();
            TipoId = TipoId.toLowerCase();


            CargarMorosidadInicial();


            repaint();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBuscar;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextFieldPlaca;
    private javax.swing.JTextField jTextFieldRemolque;
    private javax.swing.JTextField jTextFieldTotalAdeudado;
    // End of variables declaration//GEN-END:variables
}
